<?php
/* SVN FILE: $Id: fw24h_model.php 43 2009-08-25 02:20:20Z phamshantuyet@gmail.com $ */
/**
*
* @author $Author: phamshantuyet@gmail.com $
* @version $Revision: 43 $
* @lastrevision $Date: 2009-08-25 09:20:20 +0700 (Tue, 25 Aug 2009) $
* @modifiedby $LastChangedBy: phamshantuyet@gmail.com $
* @lastmodified $LastChangedDate: 2009-08-25 09:20:20 +0700 (Tue, 25 Aug 2009) $
* @filesource $URL: https://ladybirdphp.googlecode.com/svn/trunk/website/fw24h2/fw24h_model.php $
*/

class FW24H_Model {

	var $tableName = '';
	var $_primaryKey = '';
	var $_Fields = array();
	var $_cache = false;
	var $_cacheTime = 900;
	var $arrRelation = array();

	var $conn_id = false;

	static $__connection = null;
	
	
	function &getConnecttion(){
		if(!self::$__connection){
			self::$__connection = fw24h_db_connect( $GLOBALS['_FW24H_CONFIG_']);
		}
		return self::$__connection;
	}
	
	/**
	 * Constructor: Khoi tao
	 *
	 * @param string $tableName	Ten bang 
	 * @param string $p_primaryKey	Khoa chinh cua ban
	 * @return FW24H_Model
	 */
	/**
	 * FW24H_Model::FW24H_Model()
	 * 
	 * @param string $tableName
	 * @param string $p_primaryKey
	 * @return
	 */
	function FW24H_Model( $tableName='', $p_primaryKey='') {
		
		if( $tableName ){
			$this->tableName = $tableName;
		}
		if( $p_primaryKey) {
			$this->_primaryKey = $p_primaryKey;
		}

		$this->conn_id = $this->getConnecttion();
	}

	function __construct( $tableName='', $p_primaryKey='') {
		
		if( $tableName ){
			$this->tableName = $tableName;
		}
		if( $p_primaryKey) {
			$this->_primaryKey = $p_primaryKey;
		}

		$this->conn_id = $this->getConnecttion();
	}

	/**
	 * Tim kiem cac ban ghi trong bang voi cac tieu chi. Ko dung duoc khi muon join voi bang khac
	 *
	 * @param string $p_conditions	Dieu kien tim kiem
	 * @param string $p_fields	Danh sach cac truong muon lay, mac dinh la *
	 * @param string $p_order Order theo dieu kien 
	 * @param int $p_limit	So luong ban ghi can lay
	 * @param int $p_start	Bat dau tu ban ghi
	 * @return array	Mang chua ban ghi tim thay
	 */
	/**
	 * FW24H_Model::find()
	 * 
	 * @param string $p_conditions
	 * @param string $p_fields
	 * @param string $p_order
	 * @param string $p_limit
	 * @param string $p_start
	 * @return
	 */
	function find( $p_conditions='', $p_fields='*', $p_order='', $p_limit='', $p_start='') {
		$f_sql = ' ';
		if( $p_conditions) {
			$f_sql = ' WHERE '.$p_conditions;
		}
		if( $p_order) {
			$f_sql .= ' ORDER BY '.$p_order;
		}
		if( is_numeric( $p_limit)) {
			$f_sql .= ' LIMIT '.$p_limit;
		}
		if( is_numeric( $p_start)) {
			$f_sql .= ','.$p_start;
		}

		$f_sql = 'SELECT '.$p_fields.' FROM '.$this->tableName.' '.$f_sql;
		
		if( $this->_cache) {
			$this->_cache = false;
			return fw24h_db_query_cache( $f_sql, $this->conn_id, $this->_cacheTime, CONST_CACHE_SQL);
		}
		
		$rs_find = fw24h_db_query( $f_sql, $this->conn_id);

		$f_return = array();
		while( $row_find = fw24h_db_fetch_assoc( $rs_find)) {
			$f_return[] = $row_find;
		}
		fw24h_db_free_result( $rs_find);
		return $f_return;
	}

	/**
	 * FW24H_Model::findCount()
	 * 
	 * @param string $p_pid
	 * @param string $p_conditions
	 * @return
	 */
	function findCount( $p_pid='*', $p_conditions='') {
		$f_sql = ' ';
		if( $p_conditions) {
			$f_sql = ' WHERE '.$p_conditions;
		}
		
		$f_sql = 'SELECT COUNT('.$p_pid.') FROM '.$this->tableName.' '.$f_sql;
		$rs_count = fw24h_db_query( $f_sql, $this->conn_id);
		$row_count = fw24h_db_fetch_array( $rs_count, $this->conn_id);
		fw24h_db_free_result( $rs_count);
		return $row_count[0];
	}

	/**
	 * FW24H_Model::save()
	 * 
	 * @param mixed $f_data
	 * @return
	 */
	function save( $f_data) {
		$f_fields = $this->_get_full_fields();
		$f_sql_fields = '';
		$f_sql_values = '';
		reset( $f_data);
		while( list( $f_key, $f_value) = each( $f_data)) {
			if( in_array( $f_key, $f_fields)) {
				$f_sql_fields .= ' ,'.$f_key;
				$f_sql_values .= ' ,"'.$f_value.'"';
			}
		}
		$f_sql_fields = preg_replace( '#^ \,#', '', $f_sql_fields);
		$f_sql_values = preg_replace( '#^ \,#', '', $f_sql_values);
		$f_sql_insert = 'INSERT INTO '.$this->tableName.' ('.$f_sql_fields.') VALUES ('.$f_sql_values.')';
		fw24h_db_query( $f_sql_insert, $this->conn_id);
		return fw24h_db_insert_id( $this->conn_id);
	}

	/**
	 * FW24H_Model::delete()
	 * 
	 * @param mixed $id
	 * @return
	 */
	function delete( $id) {
		if( !$id) {
			return false;
		}
		$f_sql = 'DELETE FROM '.$this->tableName." WHERE ".$this->_primaryKey.'='.$id;
		fw24h_db_query( $f_sql, $this->conn_id);
		return fw24h_db_affected_rows( $this->conn_id);
	}

	/**
	 * FW24H_Model::update()
	 * 
	 * @param mixed $record
	 * @param mixed $where
	 * @return
	 */
	function update( $record, $id){
		if(!is_array($record)) return false;
		
		$f_fields = $this->_get_full_fields();

		$count = 0;
			
		foreach ($record as $key => $val)
		{
			if( in_array( $key, $f_fields)) {
				if ($count==0) $set = $key."='".$val."'";
				else $set .= ", ".$key ."='".$val."'";
				$count++;
			}
		}
		
		$query = "UPDATE ".$this->tableName." SET ".$set." WHERE ".$this->_primaryKey.'='.$id;
		fw24h_db_query( $query, $this->conn_id);
		return fw24h_db_affected_rows( $this->conn_id);
			
	} // end update

	/**
	 * FW24H_Model::update()
	 * 
	 * @param mixed $record
	 * @param mixed $where
	 * @return
	 */
	function updateByField( $record, $where){
		if(!is_array($record)) return false;
		
		$f_fields = $this->_get_full_fields();

		$count = 0;
			
		foreach ($record as $key => $val)
		{
			if( in_array( $key, $f_fields)) {
				if ($count==0) $set = $key."='".$val."'";
				else $set .= ", ".$key ."='".$val."'";
				$count++;
			}
		}
		
		$query = "UPDATE ".$this->tableName." SET ".$set." WHERE ".$where;
		fw24h_db_query( $query, $this->conn_id);
		return fw24h_db_affected_rows( $this->conn_id);
			
	} // end update

	/**
	 * FW24H_Model::execute()
	 * 
	 * @param mixed $p_sql
	 * @param bool $p_return
	 * @return
	 */
	function execute( $p_sql, $p_return=true) {
		$rs_exec = fw24h_db_query( $p_sql, $this->conn_id);
		if( $p_return) {
			$f_result = array();
			while( $row_exec = fw24h_db_fetch_assoc( $rs_exec)) {
				$f_result[] = $row_exec;
			}
			fw24h_db_free_result( $rs_exec);
			return $f_result;
		}else {
			return fw24h_db_affected_rows( $this->conn_id);
		}
	}

	/**
	 * FW24H_Model::_get_full_fields()
	 * 
	 * @return
	 */
	function _get_full_fields(){
		if( count( $this->_Fields) > 0) {
			return $this->_Fields;
		}
		$sql = 'SHOW COLUMNS FROM '.$this->tableName;
		$rs = fw24h_db_query( $sql, $this->conn_id);
		$rows = array();
		while( $row = fw24h_db_fetch_assoc( $rs)){
			$rows[] = $row['Field'];
			if( $row['Key'] == 'PRI') {
				$this->_primaryKey = $row['Field'];
			}
		}
		fw24h_db_free_result( $rs);
		return $this->_Fields = $rows;
	}

	/**
	 * FW24H_Model::get()
	 * 
	 * @param mixed $p_id
	 * @param string $p_fields
	 * @return
	 */
	function get( $p_id, $p_fields='*') {
		$v_sql = 'SELECT '.$p_fields.' FROM '.$this->tableName.' WHERE '.$this->_primaryKey.'="'.$p_id.'"';
		$rs_get = fw24h_db_query( $v_sql, $this->conn_id);
		return fw24h_db_fetch_array( $rs_get, $this->conn_id);
	}

	/**
	 * FW24H_Model::ExecuteOne()
	 * 
	 * @param mixed $p_sql
	 * @return
	 */
	function ExecuteOne( $p_sql) {
		$rs_get = fw24h_db_query( $p_sql, $this->conn_id);
		return fw24h_db_fetch_array( $rs_get, $this->conn_id);
	}

	function _is_email( $strEmail){
		$strRegular = '^[A-Za-z0-9_\.\-]+@[A-Za-z0-9_\.\-]+\.';
		$strRegular = $strRegular . '[A-Za-z0-9_\-][A-Za-z0-9_\-]+$';
		if ( !ereg( $strRegular, $strEmail)) {
			return false;
		}    	
		return true;   	
	}

	function _is_url( $url, $maxlen = 256){
		if( strlen( $url) > $maxlen) {
			return 0;
		}
		if( ereg( '(h{0,1}t{0,2}p{0,1}:{0,1}/{0,1}/{0,1})(w{0,3}\.{0,1})([aA-zZ]+)?\.{1}([aA-zZ]{2,3})(.*)', $url)) {
			return 1;
		}
		return 0;
	}

	function _is_username( $p_username, $p_allow_chars='', $p_min=4, $p_max=14) {
		$f_len = strlen( $p_username);
		
		if( $f_len < $p_min || $f_len > $p_max) {
			return false;
		}

		if( !preg_match( "#^[a-zA-Z0-9$p_allow_chars]+$#", $p_username)) {
			return false;
		}
		return true;
	}

	function _is_telephone_number( $p_tel) {
		if( preg_match( '#^[+\(\)\. 0-9\,\-]+$#', $p_tel)) {
			return true;
		}
		return false;
	}

	function _check_date( $p_date, $p_type='EN') {
		$p_type = strtoupper( $p_type);
		if( $p_type == 'EN' && ( preg_match( '#^(\d{2})\/(\d{2})\/(\d{4})$#', $p_date, $re) && $p_date == date('m/d/Y', mktime( 0, 0, 0, $re[1], $re[2], $re[3])))) {
			return true;
		}elseif( $p_type == 'VN' && preg_match( '#^(\d{2})\/(\d{2})\/(\d{4})$#', $p_date, $re) && $p_date == date('d/m/Y', mktime( 0, 0, 0, $re[2], $re[1], $re[3]))) {
			return true;
		}
		return false;
	}

	function _form_validate( $data, $p_form) {
		$f_error = array();
		$f_error['error'] = false;
		foreach( $p_form as $v_key=>$v_value) {
			if( $v_value['validate'] == 'none') {
				continue;
			}
			if( !preg_match( '#function:([a-zA-Z0-9\_]+)#', $v_value['validate'], $f_result)) {
				if( !fw24h_validate( $data[$v_key], $v_value['validate'])) {
					$f_error[$v_key]['_error'] = $v_value['error'];
					$f_error['error'] = true;
				}
			}else{
				if( !$this->$f_result[1]( $data[ $v_key])) {
					$f_error[$v_key]['_error'] = $v_value['error'];
					$f_error['error'] = true;
				}
			}
			$f_error[$v_key]['value'] = $data[$v_key];
		}
		return $f_error;
	}
}

